package com.aaa.utils;

import com.aaa.service.MouseServiceImpl;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.util.Date;

/**
 * @author ：Teacher陈（86521760@qq.com）
 * @date ：Created in 2022/6/15 9:43
 * @description：基于cglib的动态代理实现类
 * @modified By：
 * @version: 1.0
 */
public class ProxyDynamicCGlibImpl<T>  implements ProxyDynamic<T> {
    private  T target;
    public ProxyDynamicCGlibImpl() {
    }
    public ProxyDynamicCGlibImpl(T target) {
        this.target = target;
    }

    /**
     * @create by: Teacher陈（86521760@qq.com）
     * @description: 获取代理对象
     * @create time: 2022/6/15 9:42
     * @return
     */
    public T getProxyObj() {
        //1、创建字节码增强器
        Enhancer enhancer = new Enhancer();
        //2、指定需要增强的类
        enhancer.setSuperclass(target.getClass());
        //3、设置回调函数
        //  MyMethodIntercepter myMethodIntercepter = new MyMethodIntercepter();
        enhancer.setCallback(new MethodInterceptor() {
            public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
                //增强处理
                System.out.println("日志："+method.getName()+"执行了"+new Date());
                //执行目标对象的方法
                Object invokeSuper = proxy.invokeSuper(obj, args);
                return invokeSuper;
            }
        });
        //4、返回代理对象
        return (T) enhancer.create();
    }

    public static void main(String[] args) {
        ProxyDynamicCGlibImpl<MouseServiceImpl> proxyDynamicCGlib= new ProxyDynamicCGlibImpl(new MouseServiceImpl());
        MouseServiceImpl proxyObj = proxyDynamicCGlib.getProxyObj();
        proxyObj.buyMouse(300);
    }
}
